<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { formatExcelDate } from '@/utils/tree.js'
import { importEmloyee } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    handleSuccess({ header, results }) {
      console.log(header, results)
      //   2.按接口要求 组装数据
      const data = this.transExcel(results)
      console.log('按接口要求 组装数据', data)
      //   3.调用接口做上传
      this.doImport(data)
    },
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(zhObj => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj)
        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            //   后端需要的日期格式标准时间
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
          enObj[enKey] = zhObj[zhKey]
        })
        return enObj
      })
    },
    async doImport(data) {
      try {
        const res = await importEmloyee(data)
        console.log('importEmployee', res)
        this.$message.success('导入成功')
        this.$router.back()
      } catch (err) {
        console.log('importEmployee', err)
        this.message.error('导入失败')
      }
    }
  }
}
</script>
